package com.aleaho.cftrack.db.service;

import android.util.Log;

import com.aleaho.cftrack.CFTrackApplication;
import com.aleaho.cftrack.db.gen.LastLoginDao;
import com.aleaho.cftrack.db.model.LastLogin;
import com.aleaho.cftrack.utils.Constants;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/10/8.
 */

public class LastLoginService {

    private static LastLoginDao lastLoginDao = CFTrackApplication.getInstance().getDaoSession().getLastLoginDao();


    //    private static String toString(){
    //        return  "LastLoginService";
    //    }


    /**
     * 获得最后登录的用户名。
     *
     * @return
     */
    public static String getLastLoginUserName() {

        //        LastLoginDao lastLoginDao = CFTrackApplication.getInstance().getDaoSession().getLastLoginDao();


        List<LastLogin> LastLogins = lastLoginDao.loadAll();

        if (LastLogins.isEmpty()) {
            return null;
        }

        LastLogin lastLogin = LastLogins.get(0);

        return lastLogin.getUsername();
    }


    /**
     * 获得最后登录的用户名。
     *
     * @return
     */
    public static List<LastLogin> getLastLogin() {

        //        LastLoginDao lastLoginDao = CFTrackApplication.getInstance().getDaoSession().getLastLoginDao();

        List<LastLogin> lastLogins = null;
        try {
            lastLogins = lastLoginDao.loadAll();
        } catch (Exception e) {
            Log.e(Constants.TAG, e.toString());
        }


        if (lastLogins.isEmpty()) {
            return null;
        } else {
            return lastLogins;
        }
    }


    /**
     * 登录时保存最新的用户名.
     *
     * @param userName 用户名.
     * @param date     登录时间.
     * @return 保存数据库时生成的ID.
     */
    public static long insert(String userName, Date date) {

        lastLoginDao.deleteAll();
        return lastLoginDao.insert(new LastLogin(null, userName, date));

    }


    public static void deleteAll() {
        //        LastLoginDao lastLoginDao = CFTrackApplication.getInstance().getDaoSession().getLastLoginDao();

        lastLoginDao.deleteAll();
    }
}
